package com.rzico.sbl.ui.order

import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderDetailBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderBarrelData
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderLogData
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.showOrderLogDialog
import com.rzico.sbl.other.showPriceDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.member.MemberDetailActivity
import com.rzico.sbl.ui.member.MemberTicketActivity
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.glideExt.loadRoundedImage
import com.xinnuo.common_ui.utils.*
import com.xinnuo.slimadapter.SlimAdapter
import net.mikaelzero.mojito.ext.mojito
import net.mikaelzero.mojito.impl.DefaultPercentProgress
import net.mikaelzero.mojito.impl.NumIndicator
import net.mikaelzero.mojito.interfaces.IProgress
import net.mikaelzero.mojito.loader.InstanceLoader
import org.json.JSONArray
import org.json.JSONObject

class OrderDetailActivity : BaseActivity(R.layout.activity_order_detail) {

    private val mBinding by lazy { ActivityOrderDetailBinding.bind(getRootView()) }

    private lateinit var mOrderSn: String     //订单编号
    private lateinit var mShippingSn: String  //运单编号
    private var mOrderIndex: Int = -1         //列表索引

    private var mCardId = ""      //会员卡ID
    private var mMemberId = ""    //会员ID
    private var mStatus = ""      //运单状态
    private var mOrderMethod = "" //订单类型
    private var mAmount = ""       //合计金额
    private var mCreateDate = ""   //下单时间
    private var mHopeDate = ""     //预约时间
    private var mEstimateDate = "" //预计送达
    private var mDeliveryDate = "" //送达时间
    private var isShipping = false

    private var mReceivePhone = ""  //收货电话
    private var mReceiveAdress = "" //收货地址

    // 图片列表
    private var mPhotoList = ArrayList<String>()

    // 订单日志
    private val mLogList = arrayListOf<OrderLogData>()

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        initTitle(title = "订单详情", name = "打印")

        initLayout()
        initPhotoLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.detailList.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())

            addItemDecoration(
                SpaceTBDecoration(
                    top = 5f,
                    hasHeader = false,
                    hasFooter = false,
                    spaceColor = R.color.white
                )
            )

            mAdapter = SlimAdapter.creator()
                .register<OrderGoods>(R.layout.item_order_detail_list) { jector, bean, _ ->
                    jector.apply {
                        text(R.id.item_order_name, bean.name)
                        text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                        text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                        text(R.id.item_order_num, "x${bean.quantity}")

                        visibility(
                            R.id.item_order_img_label,
                            visibleValue { bean.first }
                        )

                        with<ImageView>(R.id.item_order_img) {
                            it.loadImage(bean.thumbnail)
                        }

                        with<ImageView>(R.id.item_order_img_type) {
                            when (mOrderMethod) {
                                "offline" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order03)
                                }

                                "eleme", "elemengc" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order04)
                                }

                                "meituan" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order05)
                                }

                                "nongfu" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order06)
                                }

                                "jd" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order10)
                                }

                                "taobao" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order11)
                                }

                                "pinduoduo" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order12)
                                }

                                "dummy" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order22)
                                }

                                "ali" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order26)
                                }

                                else -> it.gone()
                            }
                        }

                        with<ImageView>(R.id.item_order_img_status) {
                            it.isVisible = mHopeDate.isNotEmpty()

                            mHopeDate.notEmpty {
                                it.setImageResource(
                                    conditionIf(
                                        longValue < mEstimateDate.longValue,
                                        R.mipmap.icon_order07,
                                        R.mipmap.icon_order02
                                    )
                                )
                            }
                        }
                    }
                }
                .attachTo(this)
        }

        tvRight?.oneClick {
            if (mOrderSn.isNotEmpty()) {
                showHintDialog(
                    title = "订单打印",
                    hint = "确定要打印该订单吗？",
                    onSure = {
                        getViewModel()
                            .operateOrder(
                                BaseUrl.orderPrint,
                                mOrderSn,
                                false
                            )
                            .bindLifeCycle(getLifecycleOwner())
                            .subscribeBySuccess(
                                event = getViewModel(),
                                onSuccess = {
                                    showToast("订单打印成功！")
                                }
                            )
                    }
                )
            } else
                showToast("订单信息获取失败")
        }
    }

    private fun initPhotoLayout() {
        mBinding.apply {
            detailPhoto.also { layout ->
                layout.isNestedScrollingEnabled = false
                layout.layoutManager = FullyGridLayoutManager(baseContext, 3)
                layout.adapter = SlimAdapter.creator()
                    .register<String>(R.layout.item_photo_grid) { jector, bean, index ->
                        jector.apply {
                            gone(R.id.item_photo_del)

                            with<ImageView>(R.id.item_photo_img) {
                                it.loadRoundedImage(
                                    url = bean,
                                    radius = 10f
                                )
                            }

                            clicked {
                                layout.mojito(R.id.item_photo_img) {
                                    urls(mPhotoList)
                                    position(index, headerSize = 1, footerSize = 1)
                                    autoLoadTarget(false)
                                    setProgressLoader(object : InstanceLoader<IProgress> {
                                        override fun providerInstance(): IProgress {
                                            return DefaultPercentProgress()
                                        }
                                    })
                                    progressLoader { DefaultPercentProgress() }
                                    setIndicator(NumIndicator())
                                }
                            }
                        }
                    }
                    .attachTo(layout)
            }

            (detailPhoto.adapter as SlimAdapter).setDataList(mPhotoList)
        }
    }

    override fun initListener() {
        mOrderSn = intent.getExtra("orderSn")
        mShippingSn = intent.getExtra("shippingSn")
        mOrderIndex = intent.getIntExtra("index", -1)

        mBinding.apply {
            detailLogLl.oneClick {
                mLogList.notEmpty {
                    showOrderLogDialog(this)
                }
            }

            detailCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            detailAdress.longClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            detailAdressCopy.oneClick {
                copyStringToClip(
                    "${detailName.textTrim}\n$mReceiveAdress"
                )
                showToast("复制成功！")
            }

            detailTicketLl.oneClick {
                mCardId.notEmpty {
                    startActivityEx<MemberTicketActivity>(
                        "cardId" to mCardId,
                        "memberId" to mMemberId
                    )
                }
            }

            detailNum.longClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailNumCopy.oneClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            detailMember.oneClick {
                startActivityEx<MemberDetailActivity>(
                    "cardId" to mCardId,
                    "memberId" to mMemberId
                )
            }

            detailBtn1.oneClick {
                when (mStatus) {
                    "unpaid" -> //确认订单
                        mOrderSn.notEmpty {
                            startActivityEx<OrderConfirmActivity>(
                                "amount" to mAmount.formatDecimal(),
                                "orderSn" to mOrderSn,
                                "time" to mCreateDate.getTimeString(),
                                "index" to mOrderIndex
                            )
                        }

                    "unshipped" -> //订单发货
                        mOrderSn.notEmpty {
                            startActivityEx<OrderShipActivity>(
                                "orderSn" to mOrderSn,
                                "index" to mOrderIndex
                            )
                        }

                    "shipped" -> //订单退货
                        mOrderSn.notEmpty {
                            isShipping
                                .conditionElse(
                                    actionTrue = {
                                        startActivityEx<OrderCancelActivity>(
                                            "orderSn" to mOrderSn,
                                            "shippingSn" to mShippingSn,
                                            "index" to mOrderIndex
                                        )
                                    },
                                    actionFalse = {
                                        refuseOrder(mOrderSn, mOrderIndex)
                                    }
                                )
                        }

                    "refunding", "returning" -> //确认退款
                        mOrderSn.notEmpty {
                            refundConfirm(mOrderSn, mOrderIndex)
                        }

                    "completed" -> //虚拟商品退款
                        mOrderSn.notEmpty {
                            refundOrder(mOrderSn, mOrderIndex)
                        }
                }
            }

            detailBtn2.oneClick {
                when (mStatus) {
                    "unpaid" -> //订单改价
                        mOrderSn.notEmpty {
                            updatePrice(mOrderSn, mAmount, mOrderIndex)
                        }

                    "unshipped" -> //申请退款
                        mOrderSn.notEmpty {
                            refundOrder(mOrderSn, mOrderIndex)
                        }

                    "shipped" -> //转派
                        startActivityEx<DeliverSendActivity>(
                            "mode" to "shipped",
                            "orderSn" to mOrderSn,
                            "shippingSn" to mShippingSn,
                            "index" to mOrderIndex
                        )

                    "refunding", "returning" -> //撤销退款
                        mOrderSn.notEmpty {
                            revokeOrder(mOrderSn, mOrderIndex)
                        }
                }
            }

            detailBtn3.oneClick {
                when (mStatus) {
                    "unpaid" -> //取消订单
                        mOrderSn.notEmpty {
                            cancelOrder(mOrderSn, mOrderIndex)
                        }

                    "unshipped" -> //抛单
                        mOrderSn.notEmpty {
                            throwOrder(mOrderSn, mOrderIndex)
                        }
                }
            }
        }

        getViewModel()
            .mTicketEvent
            .observe(this) {
                mBinding.detailTicket.text = it.toString()
            }

        observe<String>("orderDetail") { getData() }
    }

    /**
     * 订单改价
     */
    private fun updatePrice(orderSN: String, amount: String, index: Int) {
        showPriceDialog(
            title = "订单改价",
            default = amount,
            onSure = { value ->
                getViewModel()
                    .updateOrder(orderSN, value)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单改价成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 取消订单
     */
    private fun cancelOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderCancel, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("取消订单成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 抛单
     */
    private fun throwOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "抛单",
            hint = "确定要抛出订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderThrow, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("抛单成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 申请退款
     */
    private fun refundOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退款成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            // 更新发货地图
                            LiveEventBus
                                .get("orderShipMap")
                                .post("refresh")

                            // 更新批量订单列表
                            LiveEventBus
                                .get("batchList")
                                .post("refresh")

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 申请退货退款
     */
    private fun refuseOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "退货退款",
            hint = "确定要退货退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderReturn, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退货退款成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 确认退款
     */
    private fun refundConfirm(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要同意退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("确认退款成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 撤销退款
     */
    private fun revokeOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "撤销退款",
            hint = "确定要撤销退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderBack, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("撤销退款成功！")

                            (index > -1)
                                .condition {
                                    // 更新订单列表
                                    LiveEventBus
                                        .get("orderList")
                                        .post("refresh")

                                    mOrderIndex = -1
                                }

                            getData()
                        }
                    )
            }
        )
    }

    /**
     * 订单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderInfo(mOrderSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)
                    mCardId = obj.optNotNull("cardId")
                    mMemberId = obj.optNotNull("memberId")
                    mStatus = obj.optNotNull("status")
                    mOrderSn = obj.optNotNull("sn")
                    mOrderMethod = obj.optNotNull("orderMethod")
                    mAmount = obj.optNotNull("amount")
                    mCreateDate = obj.optNotNull("createDate")
                    mHopeDate = obj.optNotNull("hopeDate")
                    mDeliveryDate = obj.optNotNull("deliveryDate")
                    isShipping = obj.optBoolean("isShipping")

                    mCardId.notEmpty {
                        getViewModel().ticketCount(this)
                    }

                    mBinding.apply {
                        // 美团订单金额判断
                        detailShiLl.isVisible = mOrderMethod != "meituan"
                        detailMeiLl.isVisible = mOrderMethod == "meituan"

                        detailTotal.text = obj.optNotNull("quantity")
                        detailAmount.text = obj.optNotNull("price").formatDecimal()

                        // 电子水票
                        detailShui.text = "–${
                            obj.optNotNull("exchangeDiscount")
                                .also {
                                    detailShuiLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 金币
                        detailCoin.text = "–${
                            obj.optNotNull("pointDiscount")
                                .also {
                                    detailCoinLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 优惠券
                        detailYou.text = "–${
                            obj.optNotNull("couponDiscount")
                                .also {
                                    detailYouLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 活动优惠
                        detailHuo.text = "–${
                            obj.optNotNull("activityDiscount")
                                .also {
                                    detailHuoLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 单品优惠
                        detailDan.text = "–${
                            obj.optNotNull("dragonDiscount")
                                .also {
                                    detailDanLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 会员折扣
                        detailHui.text = "–${
                            obj.optNotNull("vipDiscount")
                                .also {
                                    detailHuiLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        // 客服调价
                        detailTiao.text = "–${
                            obj.optNotNull("offsetAmount")
                                .also {
                                    detailTiaoLl.isVisible = it.doubleValue != 0.0
                                }.replace("-", "")
                        } 元"
                        // 空桶押金
                        detailBucket.text = "+${
                            obj.optNotNull("pledgePayable")
                                .also {
                                    detailBucketLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元(数量: ${obj.optNotNull("pledgeQuantity")})"
                        // 运费
                        detailFee.text = "+${
                            obj.optNotNull("freight")
                                .also {
                                    detailFeeLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        } 元"
                        obj.optNotNull("amountPaid").also {
                            // 实付款
                            detailShi.text = it.formatDecimal()
                            // 美团实收金额
                            detailMeiShou.text = it.formatDecimal()
                        }
                        // 美团实付金额
                        detailMeiFu.text = obj.optNotNull("amountPayable").formatDecimal()

                        // 转派结算金额
                        detailJie.text =
                            obj.optNotNull("settlementPrice")
                                .also {
                                    detailJieLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()

                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("areaName")
                        mReceiveAdress += objReceive.optNotNull("address")
                        // 姓名电话
                        detailName.text = "${objReceive.optNotNull("consignee")}  ${
                            when {
                                userRole in "1,2"
                                        || privacyStatus == "off" -> mReceivePhone

                                else -> mReceivePhone.phoneReplaceWithStar()
                            }
                        }"
                        // 是否拨打电话
                        detailCall.isVisible = userRole in "1,2"
                        // 收货地址
                        detailAdress.text = mReceiveAdress
                        // 查看会员
                        detailMember.isVisible =
                            userRole in "1,2"
                                    && mCardId.isNotEmpty()
                                    && mMemberId.isNotEmpty()
                        // 买家留言
                        detailMai.text =
                            obj.optNotNull("memo")
                                .notEmpty { detailMaiLl.visible() }
                        // 商家备注
                        detailCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { detailCmemoLl.visible() }
                        // 推广人
                        detailUper.text =
                            obj.optNotNull("promoter")
                                .notEmpty { detailUperLl.visible() }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单状态
                        detailStatus.text = obj.optNotNull("statusDescr")
                        // 订单编号
                        detailNum.text = mOrderSn
                        // 订单类型
                        detailType.text =
                            mOrderMethod.run {
                                notEmpty { detailTypeLl.visible() }

                                when (this) {
                                    "online" ->
                                        when (obj.optNotNull("paymentPluginId")) {
                                            "ticketPayPlugin" -> "货到付款"
                                            else -> "线上订单"
                                        }

                                    "ali" ->
                                        when (obj.optNotNull("paymentPluginId")) {
                                            "ticketPayPlugin" -> "货到付款"
                                            else -> "支付宝"
                                        }

                                    "offline" -> "人工报单"
                                    "history" -> "人工补单"
                                    "nongfu" -> "农夫APP"
                                    "meituan" -> "美团"
                                    "eleme", "elemengc" -> "饿了么"
                                    "jd" -> "京东"
                                    "taobao" -> "淘宝"
                                    "pinduoduo" -> "拼多多"
                                    "dummy" -> "自提点"
                                    else -> "其他"
                                }
                            }
                        // 支付状态
                        detailMethod.text =
                            when (mOrderMethod) {
                                "offline" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    obj.optNotNull("payMethod")
                                                        .run {
                                                            isEmpty()
                                                                .conditionElseValue(
                                                                    actionTrue = {
                                                                        detailMethodLl.visible()
                                                                        "未支付"
                                                                    },
                                                                    actionFalse = { "已支付" }
                                                                )
                                                        }
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                "online", "ali" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    detailMethodLl.visible()
                                                    "未支付"
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                else -> "已支付"
                            }
                        // 支付方式
                        detailPay.text =
                            obj.optNotNull("payMethodName")
                                .also {
                                    detailPayLl.isGone = it.isEmpty()
                                }
                        // 电子签单
                        obj.optNotNull("signature")
                            .notEmpty {
                                detailSignLl.visible()

                                Glide.with(getIContext())
                                    .load(this)
                                    .into(detailSign)
                            }
                        // 销售站点
                        (mOrderMethod == "meituan")
                            .conditionElse(
                                actionTrue = {
                                    detailShou.text =
                                        obj.optNotNull("meituanShopName")
                                            .notEmpty { detailShouLl.visible() }
                                },
                                actionFalse = {
                                    detailShou.text =
                                        obj.optNotNull("sellerName")
                                            .notEmpty { detailShouLl.visible() }
                                }
                            )
                        // 下单时间
                        detailCreate.text = mCreateDate.getTimeString()
                        // 预计送达
                        detailYue.text =
                            obj.optNotNull("estimateDate")
                                .also { mEstimateDate = it }
                                .notEmpty { detailYueLl.visible() }
                                .getTimeString()
                        // 发货时间
                        detailFa.text =
                            obj.optNotNull("shippingDate")
                                .notEmpty { detailFaLl.visible() }
                                .getTimeString()
                        // 送达时间
                        detailDa.text =
                            mDeliveryDate
                                .notEmpty { detailDaLl.visible() }
                                .getTimeString()
                        // 交易完成
                        detailWan.text =
                            obj.optNotNull("completeDate")
                                .notEmpty { detailWanLl.visible() }
                                .getTimeString()
                        // 派单留言
                        detailPai.text =
                            obj.optNotNull("shippingMemo")
                                .trimEnd('\n')
                                .notEmpty { detailPaiLl.visible() }
                        // 配送方式
                        detailDeliver.text =
                            when (mOrderMethod) {
                                "dummy" -> {
                                    detailDeliverLl.visible()
                                    "自提"
                                }

                                else -> obj.optNotNull("shippingMethod")
                                    .notEmpty { detailDeliverLl.visible() }
                            }
                        // 配送站点
                        detailZhan.text =
                            obj.optNotNull("shopName")
                                .notEmpty { detailZhanLl.visible() }
                        // 自提柜
                        detailCupboard.text =
                            (obj.optNotNull("cabinetName")
                                .notEmpty { detailCupboardLl.visible() }
                                    + obj.optNotNull("cabinetCellNo")
                                .ifNotEmpty { "-${it}号柜" })
                        // 配送人员
                        detailRen.text =
                            (obj.optNotNull("adminName")
                                    + obj.optNotNull("adminPhone").ifNotEmpty { " - $it" }
                                    )
                                .notEmpty { detailRenLl.visible() }
                        // 配送费用
                        detailPei.text =
                            obj.optNotNull("shippingFreight")
                                .also {
                                    detailPeiLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()
                        // 送货工资
                        detailSong.text =
                            obj.optNotNull("adminFreight")
                                .also {
                                    detailSongLl.isVisible = it.doubleValue > 0
                                }.formatDecimal()

                        /*---------------------- 回桶明细 ----------------------*/
                        val objBarrel = obj.optJSONArray("shippingBarrels") ?: JSONArray()
                        val barrelList = arrayListOf<OrderBarrelData>()
                        barrelList.addItems(
                            JsonUtil.toList(
                                objBarrel.toString(),
                                OrderBarrelData::class.java
                            )
                        )
                        detailDispatch.text =
                            barrelList
                                .also {
                                    detailDispatchLl.isVisible = it.isNotEmpty()
                                }
                                .joinToString("\n") {
                                    "${it.name} | 送出${it.quantity}桶 | 收回${it.returnQuantity}桶"
                                }

                        /*---------------------- 订单日志 ----------------------*/
                        val objLog = obj.optJSONArray("orderLogs") ?: JSONArray()
                        mLogList.apply {
                            clear()
                            addItems(
                                JsonUtil.toList<OrderLogData>(
                                    objLog.toString(),
                                    OrderLogData::class.java
                                ).reversed()
                            )
                        }
                        detailLog1.text = mLogList[0].createDate.getTimeString()
                        detailLog2.text = mLogList[0].content
                    }

                    /*---------------------- 商品信息 ----------------------*/
                    val objOrder = obj.optJSONArray("orderItems") ?: JSONArray()
                    mList.clear()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )

                    // 是否首单
                    val isFirst = obj.optBoolean("isFirst")
                    mList.forEach { (it as OrderGoods).first = isFirst }

                    mAdapter.setDataList(mList)

                    /*---------------------- 拍照记录 ----------------------*/
                    val objPhoto = obj.optJSONArray("shippingPhotos") ?: JSONArray()
                    mPhotoList.clear()
                    mPhotoList.addItems(
                        JsonUtil.toList(
                            objPhoto.toString(),
                            String::class.java
                        )
                    )
                    mPhotoList.notEmpty {
                        mBinding.detailPhotoLl.visible()
                        (mBinding.detailPhoto.adapter as SlimAdapter).notifyDataSetChanged()
                    }

                    (userRole in "1,2,10")
                        .condition {
                            mBinding.apply {
                                when (mStatus) {
                                    "unpaid" -> {
                                        detailBtn1.text = "确认订单"
                                        detailBtn2.text = "改价"
                                        detailBtn3.text = "取消订单"

                                        detailBtn1.visible()
                                        detailBtn2.visible()
                                        detailBtn3.visible()
                                        detailBottom.visible()
                                    }

                                    "unshipped" -> {
                                        detailBtn1.text = "发货"
                                        detailBtn2.text = "退款"
                                        detailBtn3.text = "抛单"

                                        detailBtn1.visible()
                                        detailBtn2.isVisible = userRole == "1"
                                        detailBtn3.isVisible = getBoolean("canRob")
                                        detailBottom.visible()
                                    }

                                    "shipped" -> {
                                        detailBtn1.text = when {
                                            isShipping -> {
                                                detailBtn1.visible()
                                                "核销"
                                            }

                                            userRole == "1" -> {
                                                detailBtn1.visible()
                                                "退货退款"
                                            }

                                            else -> {
                                                detailBtn1.gone()
                                                ""
                                            }
                                        }

                                        detailBtn2.text = "转派"

                                        detailBtn2.isVisible = mDeliveryDate.isEmpty()
                                        detailBtn3.gone()
                                        detailBottom.visible()
                                    }

                                    "refunding", "returning" -> {
                                        detailBtn1.text = "确认退款"
                                        detailBtn2.text = "撤销"

                                        detailBtn1.isVisible = userRole == "1"
                                        detailBtn2.visible()
                                        detailBtn3.gone()
                                        detailBottom.visible()
                                    }

                                    "completed" -> {
                                        val shipMethod = obj.optNotNull("shippingMethodId")
                                        val completeDate =
                                            obj.optNotNull("completeDate").longValue
                                        val currentDate = System.currentTimeMillis()

                                        detailBtn1.text = "退款"

                                        detailBtn1.isVisible =
                                            userRole == "1"
                                                    && shipMethod == "pickup"
                                                    && (completeDate + 3 * 24 * 60 * 60 * 1000 > currentDate)
                                        detailBtn2.gone()
                                        detailBtn3.gone()
                                        detailBottom.visible()
                                    }

                                    else -> detailBottom.gone()
                                }
                            }
                        }
                }
            )
    }

}